﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using AutoplanetaTaskManager.Daos;
using AutoplanetaTaskManager.Daos.EntityFramework;
using AutoplanetaTaskManager.Models;
using AutoplanetaTaskManager.Utilities;

namespace AutoplanetaTaskManager.Views.Components
{
    public class PostItemComponent : GroupBox
    {
        private const int RowHeight = 20;

        private readonly int _postId;
        private DateTime _dateTime;

        private readonly DataGridView _mainDataGridView;
        private readonly Button _infoButton;
        private readonly Button _addButton;
        private readonly Button _removeButton;

        private readonly ITaskDao _taskDao = new TaskDao();

        public PostItemComponent(int postId)
        {
            _postId = postId;

            Location = new Point(0, 0);
            Size = new Size(250, 320);
            Text = new PostDao().Get(_postId).Name;
            BackColor = Color.LightCyan;

            _mainDataGridView =
                new DataGridView
                    {
                        Location = new Point(6, 19), Size = new Size(228, 266),
                        SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                        MultiSelect = false, ReadOnly = true, AutoGenerateColumns = false, 
                        RowHeadersVisible = false, TabIndex = 0
                    };
            _mainDataGridView.SelectionChanged += MainDataGridViewOnSelectionChanged;
            _mainDataGridView.DataBindingComplete += MainDataGridViewOnDataBindingComplete;
            Controls.Add(_mainDataGridView);

            DataGridViewTextBoxColumn idColumn =
                new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "Id", Name = "Id", HeaderText = "Id", Visible = false
                    };
            _mainDataGridView.Columns.Add(idColumn);
            DataGridViewTextBoxColumn hourColumn =
                new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "Time", Name = "Time", HeaderText = "Время", 
                        Width = 46, Resizable = DataGridViewTriState.False
                    };
            _mainDataGridView.Columns.Add(hourColumn);
            DataGridViewTextBoxColumn ordererColumn =
                new DataGridViewTextBoxColumn
                    {
                        DataPropertyName = "Orderer", Name = "Orderer", HeaderText = "Клиент",
                        Width = 180, Resizable = DataGridViewTriState.False
                    };
            _mainDataGridView.Columns.Add(ordererColumn);

            _infoButton =
                new Button
                    {
                        Location = new Point(6, 291), Size = new Size(75, 23), TabIndex = 1,
                        Text = "Просмотр", UseVisualStyleBackColor = true
                    };
            _infoButton.Click += InfoButtonOnClick;
            Controls.Add(_infoButton);

            _addButton =
                new Button
                    {
                        Location = new Point(87, 291), Size = new Size(75, 23), TabIndex = 2,
                        Text = "Добавить", UseVisualStyleBackColor = true
                    };
            _addButton.Click += AddButtonOnClick;
            Controls.Add(_addButton);

            _removeButton =
                new Button
                    {
                        Location = new Point(168, 291), Size = new Size(75, 23), TabIndex = 3,
                        Text = "Удалить", UseVisualStyleBackColor = true
                    };
            _removeButton.Click += RemoveButtonOnClick;
            Controls.Add(_removeButton);
        }

        private void MainDataGridViewOnDataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs dataGridViewBindingCompleteEventArgs)
        {
            foreach (DataGridViewRow row in _mainDataGridView.Rows)
            {
                int id = (int)row.Cells[0].Value;
                if (id > 0)
                    if ((bool)_taskDao.Get(id).Finished) row.DefaultCellStyle.BackColor = Color.Chartreuse;
                    else row.DefaultCellStyle.BackColor = Color.Red;
            }
        }

        private void MainDataGridViewOnSelectionChanged(object sender, EventArgs eventArgs)
        {
            if (_mainDataGridView.SelectedRows != null && _mainDataGridView.SelectedRows.Count > 0)
                if ((int)_mainDataGridView.SelectedRows[0].Cells[0].Value > 0)
                {
                    _infoButton.Enabled = true;
                    _addButton.Enabled = false;
                    _removeButton.Enabled = true;
                }
                else
                {
                    _infoButton.Enabled = false;
                    _addButton.Enabled = true;
                    _removeButton.Enabled = false;
                }
        }

        private void InfoButtonOnClick(object sender, EventArgs eventArgs)
        {
            if (_mainDataGridView.SelectedRows[0] != null &&
                (int)_mainDataGridView.SelectedRows[0].Cells[0].Value > 0)
            {
                int taskId = (int)_mainDataGridView.SelectedRows[0].Cells[0].Value;
                new InfoTaskForm(this, taskId).ShowDialog();
            }
        }

        private void AddButtonOnClick(object sender, EventArgs eventArgs)
        {
            if (_mainDataGridView.SelectedRows[0] != null &&
                (int)_mainDataGridView.SelectedRows[0].Cells[0].Value <= 0)
            {
                new AddTaskForm(this, _postId, 
                    Converter.DateTimeToYMDH(_dateTime, _mainDataGridView.SelectedRows[0].Cells[1].Value.ToString())).ShowDialog();
            }
        }

        private void RemoveButtonOnClick(object sender, EventArgs eventArgs)
        {
            if (_mainDataGridView.SelectedRows[0] != null &&
                (int)_mainDataGridView.SelectedRows[0].Cells[0].Value > 0)
            {
                int taskId = (int)_mainDataGridView.SelectedRows[0].Cells[0].Value;
                new RemoveTaskForm(this, taskId).ShowDialog();
            }
        }

        /// <summary>
        /// Метод для настройки содержимого таблицы заданий. Вызывайте даный метод при запуске приложения и каждый раз после изменения содержимого базы данных
        /// </summary>
        /// <param name="dateTime">Текущая дата</param>
        public void SetContent(DateTime dateTime)
        {
            _dateTime = dateTime;

            DateTime startDateTime = Converter.DateTimeToYMDH(_dateTime, Config.StartHour);
            DateTime finishDateTime = Converter.DateTimeToYMDH(_dateTime, Config.FinishHour);

            List<PostItemModel> postItemModels = new List<PostItemModel>();
            for (DateTime time = startDateTime; time <= finishDateTime; time += TimeSpan.FromMinutes(30))
            {
                Task task = _taskDao.Get(_postId, time);

                if (task != null)
                {
                    postItemModels.Add(
                            new PostItemModel
                            {
                                Id = task.Id,
                                Time = string.Format("{0:HH:mm}", time),
                                Orderer = task.ClientName
                            });

                    DateTime stDt2 = time + TimeSpan.FromMinutes(30);
                    DateTime fnDt2 = time + TimeSpan.FromHours((double) task.CountHours);
                    for (DateTime time2 = stDt2; time2 < fnDt2; time2 += TimeSpan.FromMinutes(30))
                    {
                        postItemModels.Add(
                            new PostItemModel
                                {
                                    Id = task.Id,
                                    Time = string.Format("{0:HH:mm}", time2),
                                    Orderer = "===>> " + task.ClientName
                                });
                        time = time2;
                    }
                }
                else
                {
                    postItemModels.Add(
                        new PostItemModel { Id = 0, Time = string.Format("{0:HH:mm}", time), Orderer = "---" });
                }
            }
            _mainDataGridView.RowTemplate.Height = RowHeight;
            _mainDataGridView.DataSource = postItemModels;
        }

        public void UpdateContent()
        {
            SetContent(_dateTime);
        }
    }
}
